#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
请求体示例
演示了如何使用请求体
"""

from fastapi import FastAPI
from pydantic import BaseModel
from typing import Union

app = FastAPI()

# 定义 Pydantic 模型
class Item(BaseModel):
    name: str
    description: Union[str, None] = None
    price: float
    tax: Union[float, None] = None

@app.post("/items/")
async def create_item(item: Item):
    return item

@app.put("/items/{item_id}")
async def update_item(item_id: int, item: Item):
    return {"item_id": item_id, **item.dict()}

# 请求体、路径参数和查询参数的组合
@app.put("/items-combined/{item_id}")
async def update_item_combined(
    item_id: int, 
    item: Item, 
    q: Union[str, None] = None
):
    result = {"item_id": item_id, **item.dict()}
    if q:
        result.update({"q": q})
    return result

# 使用模型
@app.post("/items-with-tax/")
async def create_item_with_tax(item: Item):
    item_dict = item.dict()
    if item.tax is not None:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8003, log_level="info")